//
//  FSScrollContentViewController.m
//  FSScrollViewNestTableViewDemo
//
//  Created by huim on 2017/5/23.
//  Copyright © 2017年 fengshun. All rights reserved.
//

#import "FSScrollContentViewController.h"
#import "PS_ReMenHuiDaModel.h"
#import "PS_HotTitleTableViewCell.h"
#import "PS_HotContentTableViewCell.h"
#import "PS_HotImagesTableViewCell.h"
#import "PS_HotVideoTableViewCell.h"
#import "SVPullToRefresh.h"
#import "PS_SquareDetailViewController.h"

@interface FSScrollContentViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSString *requstType;
}
@property (nonatomic, assign) BOOL fingerIsTouch;
@property (nonatomic, strong)UIView * footerView;


@property (nonatomic, strong)NSMutableArray * reMenHuiDaArray;

@end

@implementation FSScrollContentViewController
- (NSMutableArray *)reMenHuiDaArray{
    
    if (_reMenHuiDaArray == nil) {
        
        _reMenHuiDaArray = [NSMutableArray array];
    }
    return _reMenHuiDaArray;
}

- (UIView *)footerView{
    
    if (_footerView == nil) {
        
        _footerView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.tableView.frame), SCREEN_WIDTH, 30)];
        _footerView.backgroundColor = RGBCOLOR(238, 238, 238);
        UILabel * lable = [[UILabel alloc]initWithFrame:CGRectMake(0, 7, SCREEN_WIDTH, 15)];
        lable.text = @"已经到底了~~";
        lable.font = [UIFont systemFontOfSize:13];
        lable.textAlignment = NSTextAlignmentCenter;
        lable.textColor = RGBCOLOR(153, 153, 153);
        [_footerView addSubview:lable];
    }
    
    return _footerView;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSLog(@"---%@",self.title);
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = RGBCOLOR(238, 238, 238);
    [self setupSubViews];
}

- (void)setupSubViews
{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds),SCREEN_HEIGHT-kTabBarHeight) style:UITableViewStylePlain];
    _tableView.backgroundColor =[UIColor clearColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle =UITableViewCellSeparatorStyleNone;
//    _tableView.tableFooterView = self.footerView;
//    _tableView.bounces = NO;
    [self.view addSubview:_tableView];
    __weak typeof(self) weakSelf = self;
    [self.tableView addInfiniteScrollingWithActionHandler:^{
        [weakSelf insertRowAtBottom];
    }];
}


- (void)insertRowAtTop
{
    NSLog(@"下拉刷新");
    _currentPage = 1;
    _totalPage = 1;
    
    [self requestDataWithType:requstType];
}

- (void)insertRowAtBottom
{

    NSLog(@"上拉刷新");
    if (_currentPage > _totalPage)
    {
        [self.tableView.infiniteScrollingView stopAnimating];
        return;
    }
    [self requestDataWithType:requstType];
}

#pragma mark Setter
- (void)setIsRefresh:(BOOL)isRefresh
{
    _isRefresh = isRefresh;
    [self insertRowAtTop];
}

#pragma mark UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.reMenHuiDaArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PS_ReMenHuiDaModel * model = [self.reMenHuiDaArray objectAtIndex:indexPath.row];
    
    if (model.view_type == 1) {
        
        return 90;
        
    }else if (model.view_type == 2){
        
        return 130;
        
    }else if(model.view_type == 3){
        
        return 155;
        
    }else{
        
        return 275;
    }

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PS_ReMenHuiDaModel * model = [self.reMenHuiDaArray objectAtIndex:indexPath.row];
    
    if (model.view_type  == 1) {
        
        
        PS_HotTitleTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"PS_HotTitleTableViewCell"];
        if (cell == nil) {
            
            cell = [[[NSBundle mainBundle]loadNibNamed:@"PS_HotTitleTableViewCell" owner:self options:nil]objectAtIndex:0];
            
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setDataForCell:model];
        return cell;
        
        
    }else if(model.view_type  == 2){
        
        PS_HotContentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"PS_HotContentTableViewCell"];
        if (cell == nil) {
            
            cell = [[[NSBundle mainBundle]loadNibNamed:@"PS_HotContentTableViewCell" owner:self options:nil]objectAtIndex:0];
            
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setDataForCell:model];
        return cell;
        
        
        
    }else if(model.view_type  == 3){
        
        PS_HotImagesTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"PS_HotImagesTableViewCell"];
        if (cell == nil) {
            
            cell = [[[NSBundle mainBundle]loadNibNamed:@"PS_HotImagesTableViewCell" owner:self options:nil]objectAtIndex:0];
            
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setDataForCell:model];
        return cell;
        
        
    }else{
        
        PS_HotVideoTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"PS_HotVideoTableViewCell"];
        if (cell == nil) {
            
            cell = [[[NSBundle mainBundle]loadNibNamed:@"PS_HotVideoTableViewCell" owner:self options:nil]objectAtIndex:0];
            
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setDataForCell:model];
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    PS_ReMenHuiDaModel * model = [self.reMenHuiDaArray objectAtIndex:indexPath.row];
    PS_SquareDetailViewController * VC = [[PS_SquareDetailViewController alloc]init];
    VC.type = model.view_type;
    VC.articleID = model.articleid;
    [self.navigationController pushViewController:VC animated:YES];
}
#pragma mark UIScrollView
//判断屏幕触碰状态
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
//    DebugLog(@"接触屏幕");
    self.fingerIsTouch = YES;
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
//    DebugLog(@"离开屏幕");
    self.fingerIsTouch = NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (!self.vcCanScroll) {
        scrollView.contentOffset = CGPointZero;
    }
    if (scrollView.contentOffset.y <= 0) {
//        if (!self.fingerIsTouch) {//这里的作用是在手指离开屏幕后也不让显示主视图，具体可以自己看看效果
//            return;
//        }
        self.vcCanScroll = NO;
        scrollView.contentOffset = CGPointZero;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"leaveTop" object:nil];//到顶通知父视图改变状态
    }
    self.tableView.showsVerticalScrollIndicator = _vcCanScroll?YES:NO;
}


#pragma mark--获取数据
- (void)requestDataWithType:(NSString*)type{
    
    requstType =type;
    [self requestData];
}

- (void)requestData{
    
    NSString *page = [NSString stringWithFormat:@"%ld",_currentPage];
    [Utils post:ARTICLEINDEX parameters:@{@"type":requstType,@"page":page} success:^(NSInteger recode, id jsonObject) {
        
        if (self.currentPage == 1) {
            
            if (self.reMenHuiDaArray.count>0) {
                [self.reMenHuiDaArray removeAllObjects];
            }
        }
        
        NSArray * articleArr = [jsonObject objectForKey:@"data"];
        NSInteger totalNum = [[jsonObject objectForKey:@"totole_page"] integerValue];
        for (NSDictionary *dic  in articleArr) {
            
            PS_ReMenHuiDaModel * model = [PS_ReMenHuiDaModel mj_objectWithKeyValues:dic];
            model.articleid = [dic objectForKey:@"id"];
            [self.reMenHuiDaArray addObject:model];
            
        }
        
        [self.tableView reloadData];
        
        if (self.reMenHuiDaArray.count>0) {
            self.totalPage = totalNum;
        }
        NSLog(@"请求类型是%@ 请求的第%ld页 总共%lu个数据",self->requstType,self.currentPage,self.reMenHuiDaArray.count);
        
        
        /**数据请求成功之后当前页数+1**/
        self.currentPage++;
        
        if (self.returnRefreshBlock) {
            self.returnRefreshBlock(YES);
        }
        [self.tableView.pullToRefreshView stopAnimating];
        [self.tableView.infiniteScrollingView stopAnimating];
     
        if (self.currentPage>self.totalPage) {
            
            if (self.tableView.contentSize.height>self.tableView.frame.size.height) {
                self.tableView.tableFooterView =self.footerView;
            }else{
                self.tableView.tableFooterView =nil;
            }
            
        }else{
            self.tableView.tableFooterView =nil;
            
        }
        
    } failure:^(NSInteger recode, NSError *error) {
        if (self.returnRefreshBlock) {
            self.returnRefreshBlock(NO);
        }
        [self.tableView.pullToRefreshView stopAnimating];
        [self.tableView.infiniteScrollingView stopAnimating];

    }];
}
@end
